package com.elder.business.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.*;
import com.elder.business.mapper.*;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.enums.ApartmentType;
import com.elder.common.enums.BedType;
import com.elder.common.enums.RoomType;
import com.elder.common.utils.DateUtils;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.elder.business.service.IElderlyApartmentBedsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 床位信息Service业务层处理
 * 
 * @author elder
 * @date 2023-11-26
 */
@Service
public class ElderlyApartmentBedsServiceImpl implements IElderlyApartmentBedsService 
{
    @Autowired
    private ElderlyApartmentBedsMapper elderlyApartmentBedsMapper;
    @Autowired
    private ApartmentRoomInfoMapper apartmentRoomInfoMapper;
    @Autowired
    private ElderlyapartmentMapper elderlyapartmentMapper;
    @Autowired
    private ApartmentDictMapper apartmentDictMapper;
    @Autowired
    private ElderlyInfoMapper elderlyInfoMapper;
    @Autowired
    private MemberInfoMapper memberInfoMapper;

    /**
     * 查询床位信息
     * 
     * @param id 床位信息主键
     * @return 床位信息
     */
    @Override
    public JSONObject selectElderlyApartmentBedsById(Long id)
    {
        ElderlyApartmentBeds apartmentBeds = elderlyApartmentBedsMapper.selectElderlyApartmentBedsById(id);
        ApartmentRoomInfo apartmentRoomInfo = apartmentRoomInfoMapper.getApartmentRoomInfoByRoomId(apartmentBeds.getRoomId());
        //获取公寓信息
        List<Elderlyapartment> allApartmentInfo = elderlyapartmentMapper.getAllApartmentInfo();
        Map<Long, String> apartmentMap = allApartmentInfo.stream().collect(Collectors.toMap(Elderlyapartment::getApartmentId, Elderlyapartment::getApartmentName));
        ElderlyInfo elder = elderlyInfoMapper.getElderInfoByElderId(apartmentBeds.getElderId());
        JSONObject obj = new JSONObject();
        obj.put("id", StringNewUtils.formatStr(apartmentBeds.getId()));
        obj.put("apartmentId", StringNewUtils.long2Str(apartmentBeds.getApartmentId()));
        obj.put("apartmentName", apartmentMap.get(apartmentBeds.getApartmentId()));
        obj.put("roomId", StringNewUtils.long2Str(apartmentBeds.getRoomId()));
        obj.put("roomCode", apartmentRoomInfo.getRoomCode());
        obj.put("bedCode", apartmentBeds.getBedCode());
        obj.put("elderId", StringNewUtils.long2Str(apartmentBeds.getElderId()));
        obj.put("elderName",Objects.isNull(elder)?"":elder.getElderName());
        obj.put("bedStatus", apartmentBeds.getBedStatus());
        obj.put("notes", apartmentBeds.getNotes());
        obj.put("nurseId", StringNewUtils.long2Str(apartmentBeds.getNurseId()));
        return obj;
    }

    /**
     * 查询床位信息列表
     * 
     * @param elderlyApartmentBeds 床位信息
     * @return 床位信息
     */
    @Override
    public List<JSONObject> selectElderlyApartmentBedsList(ElderlyApartmentBeds elderlyApartmentBeds)
    {
        List<ElderlyApartmentBeds> bedsList = elderlyApartmentBedsMapper.selectElderlyApartmentBedsList(elderlyApartmentBeds);
        List<JSONObject> result = bedsList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("Id", v.getId());
            obj.put("apartmentId", v.getApartmentId());
            obj.put("roomId", v.getRoomId());
            obj.put("bedCode", v.getBedCode());
            obj.put("elderId", v.getElderId());
            obj.put("bedStatus", v.getBedStatus());
            obj.put("notes", v.getNotes());
            obj.put("nurseId", v.getNurseId());
            return obj;
        }).collect(Collectors.toList());
        return result;
    }

    /**
     * 新增床位信息
     * 
     * @param elderlyApartmentBeds 床位信息
     * @return 结果
     */
    @Override
    public int insertElderlyApartmentBeds(ElderlyApartmentBeds elderlyApartmentBeds)
    {
        elderlyApartmentBeds.setId(SnowGenerator.getId());
        elderlyApartmentBeds.setCreateTime(DateUtils.getLongTime());
        return elderlyApartmentBedsMapper.insertElderlyApartmentBeds(elderlyApartmentBeds);
    }

    /**
     * 修改床位信息
     * 
     * @param elderlyApartmentBeds 床位信息
     * @return 结果
     */
    @Override
    public int updateElderlyApartmentBeds(ElderlyApartmentBeds elderlyApartmentBeds)
    {
        elderlyApartmentBeds.setUpdateTime(DateUtils.getLongTime());
        return elderlyApartmentBedsMapper.updateElderlyApartmentBeds(elderlyApartmentBeds);
    }

    /**
     * 批量删除床位信息
     * 
     * @param ids 需要删除的床位信息主键
     * @return 结果
     */
    @Override
    public int deleteElderlyApartmentBedsByIds(Long[] ids)
    {
        return elderlyApartmentBedsMapper.deleteElderlyApartmentBedsByIds(ids);
    }

    /**
     * 删除床位信息信息
     * 
     * @param id 床位信息主键
     * @return 结果
     */
    @Override
    public int deleteElderlyApartmentBedsById(Long id)
    {
        return elderlyApartmentBedsMapper.deleteElderlyApartmentBedsById(id);
    }

    /***
     * @description 床位调整
     * @param elderId
     * @param roomId
     * @param bedCode
     * @return Integer
     * @author zyk
     * @date 2023/12/6 17:16
     */
    @Override
    @Transactional
    public JSONObject adjustElderBedInfo(Long elderId, Long roomId, String bedCode) {
        //判断是否已住满
        ElderlyApartmentBeds elderBedInfo = elderlyApartmentBedsMapper.getElderRoomBedInfoByElderId(elderId);
        ApartmentRoomInfo roomInfo = apartmentRoomInfoMapper.getApartmentRoomInfoByRoomId(elderBedInfo.getRoomId());
        //删除现有的老人床位信息
        elderlyApartmentBedsMapper.updatedelElderRoomBedInfo(elderId);
        if(Objects.equals(roomInfo.getRoomStatus(), RoomType.ROOM_FULL.getValue())){
            //修改房间状态
            apartmentRoomInfoMapper.updateApartmentRoomPeopleInfo(elderBedInfo.getRoomId(),RoomType.ROOM_NOT_FULL.getValue());
        }
        //添加 调整后的床位信息
        elderlyApartmentBedsMapper.updateElderlyApartmentBedInfo(roomId,elderBedInfo.getId(),elderId);
        //根据roomId 获取room情况 是否满员
        List<ElderlyApartmentBeds> bedsList = elderlyApartmentBedsMapper.getElderRoomBedInfo(Arrays.asList(roomId));
        List<ElderlyApartmentBeds> beds = bedsList.stream().filter(rel -> rel.getBedStatus() == 0).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(beds)){
            //满员 更新 房间入住情况
            apartmentRoomInfoMapper.updateApartmentRoomPeopleInfo(roomId,1);
        }
        //判断是否改变公寓
        ApartmentRoomInfo apartRoomInfo = apartmentRoomInfoMapper.getApartmentRoomInfoByRoomId(roomId);
        if(!Objects.equals(roomInfo.getApartmentId(),apartRoomInfo.getApartmentId())){
            elderlyapartmentMapper.updateElderlyapartmentLiveNum(roomInfo.getApartmentId(),-1);
            elderlyapartmentMapper.updateElderlyapartmentLiveNum(apartRoomInfo.getApartmentId(),1);
        }
        JSONObject obj = new JSONObject();
        obj.put("code",200);
        obj.put("msg","操作成功");
        return obj;

    }

    /**
     * @description 查询床位信息列表
     * @param bedStatus
     * @param pageNum
     * @param pageSize
     * @return TableDataInfo
     * @author zyk
     * @date 2023/12/6 17:16
     */
    @Override
    public TableDataInfo getElderlyApartmentBedsList(String elderName, Integer bedStatus, String roomCode, Integer pageNum, Integer pageSize) {
        List<Long> elderIds = null;
        List<Long> roomIds = null;
        if(!StringNewUtils.isEmpty(elderName)) {
            List<ElderlyInfo> elderinfoList = elderlyInfoMapper.getElderinfoList(elderName);
            elderIds = elderinfoList.stream().map(ElderlyInfo::getElderId).collect(Collectors.toList());
        }
        if(!StringNewUtils.isEmpty(roomCode)){
            List<ApartmentRoomInfo> roomList = apartmentRoomInfoMapper.getApartmentRoomListByRoomCode(roomCode);
            roomIds = roomList.stream().map(ApartmentRoomInfo::getRoomId).collect(Collectors.toList());
        }
        PageHelper.startPage(pageNum,pageSize);
        List<ElderlyApartmentBeds> list = elderlyApartmentBedsMapper.getElderRoomBedInfoList(elderIds,bedStatus,roomIds);
        PageInfo<ElderlyApartmentBeds> pageInfo = new PageInfo<>(list);
        List<ElderlyApartmentBeds> bedsList = pageInfo.getList();
        //获取公寓名称
        Map<Long, String> apartMap = elderlyapartmentMapper.getAllApartmentInfo()
                .stream().collect(Collectors.toMap(Elderlyapartment::getApartmentId, Elderlyapartment::getApartmentName));

        //获取老人信息
        Map<Long, String> elderMap = elderlyInfoMapper.getAllElderList().stream().collect(Collectors.toMap(ElderlyInfo::getElderId, ElderlyInfo::getElderName));
        //获取字典信息
        Map<Integer, String> dictMap = apartmentDictMapper.getApartmentDictInfo(ApartmentType.ROOM_TYPE.getValue()).stream().collect(Collectors.toMap(ApartmentDict::getCode, ApartmentDict::getName));
        //获取房间信息
        List<ApartmentRoomInfo> roomInfoList = apartmentRoomInfoMapper.getRoomIfoList();
        Map<Long, ApartmentRoomInfo> roomMap = roomInfoList.stream().collect(Collectors.toMap(ApartmentRoomInfo::getRoomId, Function.identity()));
        List<Long> nurseIds = roomInfoList.stream().filter(rel-> Objects.nonNull(rel.getNurseId())).map(ApartmentRoomInfo::getNurseId).collect(Collectors.toList());
        //获取员工信息
        Map<Long,String> memberMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(nurseIds)) {
            List<MemberInfo> memberList = memberInfoMapper.getMemberListByMemberIds(nurseIds);
            memberMap = memberList.stream().collect(Collectors.toMap(MemberInfo::getMemberId, MemberInfo::getMemberName));
        }
        if(CollectionUtils.isNotEmpty(bedsList)){
            Map<Long, String> finalMemberMap = memberMap;
            List<JSONObject> bedInfoList = bedsList.stream().map(v -> {
                JSONObject obj = new JSONObject();
                obj.put("elderName", elderMap.get(v.getElderId()));
                obj.put("apartmentId", StringNewUtils.long2Str(v.getApartmentId()));
                obj.put("apartmentName", apartMap.get(roomMap.get(v.getRoomId()).getApartmentId()));
                obj.put("bedCode", v.getBedCode());
                obj.put("bedStatus", BedType.getCnName(v.getBedStatus()));
                obj.put("elderId", StringNewUtils.long2Str(v.getElderId()));
                obj.put("nurseId", StringNewUtils.long2Str(v.getNurseId()));
                obj.put("nurseName", finalMemberMap.get(roomMap.get(v.getRoomId()).getNurseId()));
                obj.put("notes", v.getNotes());
                obj.put("roomId", StringNewUtils.long2Str(v.getRoomId()));
                obj.put("roomCode", roomMap.get(v.getRoomId()).getRoomCode());
                obj.put("roomType",dictMap.get(roomMap.get(v.getRoomId()).getRoomType()));
                obj.put("updateTime", v.getUpdateTime());
                obj.put("createTime", v.getCreateTime());
                obj.put("Id", StringNewUtils.long2Str(v.getId()));
                return obj;
            }).collect(Collectors.toList());
            TableDataInfo dataInfo = new TableDataInfo();
            dataInfo.setCode(200);
            dataInfo.setMsg("success");
            dataInfo.setRows(bedInfoList);
            dataInfo.setTotal(pageInfo.getTotal());
            return dataInfo;
        }
        return new TableDataInfo();
    }
}
